//和守护进程相关
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "function.h"
#include "macro.h"
#include "configure.h"

//守护进程初始化
int Daemon() {
	switch (fork()) {
	case -1:
		LogErrorCore(LOG_EMERG, errno, "Daemon()中fork()失败!");
		return -1;
	case 0:
		break;
	default:
		return 1;
	}

	parent_pid = current_pid;
	current_pid = getpid();

	//脱离终端
	if(setsid() == -1) {
		LogErrorCore(LOG_EMERG, errno, "Daemon()中setsid()失败!");
		return -1;
	}
	
	//设置为0，不限制文件权限
	umask(0);

	//打开黑洞设备
	int fd = open("/dev/null", O_RDWR);
	if(fd == -1) {
		LogErrorCore(LOG_EMERG, errno, "Daemon()中open(\"/dev/null\")失败!");
		return -1;
	}
	//使黑洞设备成为标准输入和输出
	if(dup2(fd,STDIN_FILENO) == -1) {
		LogErrorCore(LOG_EMERG, errno, "Daemon()中dup2(STDIN)失败!");
		return -1;
	}
	if(dup2(fd,STDOUT_FILENO) == -1) {
		LogErrorCore(LOG_EMERG, errno, "Daemon()中dup2(STDOUT)失败!");
		return -1;
	}
	if(fd > STDERR_FILENO) {
		if(close(fd) == -1) {
			LogErrorCore(LOG_EMERG, errno, "Daemon()中close(fd)失败!");
			return -1;
		}
	}
	return 0;
}
